<template>
  <uni-forms :modelValue="formField" ref="formRef" :rules="currentDataForm.rules">
    
    <template v-for="(item, index) in currentDataForm.fieldDataList" :key="index">
      <uni-forms-item
        :label="item.label"
        :name="item.field"
        :required="item.rules && item.rules.some(sitem => sitem.required)"
        label-align="center"
        :label-width="item.labelWidth || currentDataForm.labelWidth"
        v-bind="item.formItemOptions"
        v-if="item.isShow !== false">
        <slot :name="item.template" v-if="item.type === 'template'" :obj="item"></slot>
        <IFormItem :formField="formField" :currentFildData="item" @changeSelectFun="changeSelectFun"></IFormItem>
      </uni-forms-item>
    </template>
  </uni-forms>
</template>
<script setup lang="ts">
import { FieldListInterFace, FormInterFace } from '#/form/IForm';
import { computed, PropType, ref } from 'vue';
import IFormItem from './IFormItem.vue';
const props = defineProps({
  formData: {
    type: Object as PropType<FormInterFace<any>>,
    required: true
  }
});
const formRef = ref();
const formField = computed(() => props.formData.form);
const currentDataForm = computed(() => {
  const rules: any = {};
  const fieldDataList = props.formData.fieldDataList.filter((item: FieldListInterFace) => item.isShow !== false);
  fieldDataList.forEach((item: FieldListInterFace) => {
    if (item.rules && item.rules.length > 0) {
      rules[item.field] = { rules: item.rules };
    }
  });
  return {
    labelWidth: props.formData.labelWidth,
    form: props.formData.form,
    fieldDataList: fieldDataList,
    rules: rules,
    options: props.formData.options
  };
});
//选择回调
const changeSelectFun = (data: any): void => data.item.callback && data.item.callback(data.data, data.item, props.formData, data.extra);
// 清空表单验证
const resetForm = () => formRef.value.resetFields();
// 清空表单验证
const clearValidate = () => formRef.value.clearValidate();
// 获取表单提交内容
const onSubmit = () => {
  return new Promise((resolve, reject) => {
    formRef.value
      .validate()
      .then(res => {
        debugger;
      })
      .catch(() => reject(false));

    // formRef.value
    //   .validate()
    //   .then(() => resolve({ form: currentDataForm.value.form, dataForm: currentDataForm.value }))
    //   .catch(() => reject(false));
  });
};
// 暴露变量
defineExpose({
  resetForm,
  clearValidate,
  onSubmit
});
</script>
<style lang="scss"></style>
